package cn.jsxz.controller;

import cn.jsxz.common.utils.ResultUtil;
import cn.jsxz.dto.Result;
import cn.hutool.setting.dialect.Props;
import com.alibaba.fastjson.JSONObject;
import com.qiniu.common.Zone;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @auther: Zy
 * @method UploadController
 * 功能描述: 文件上传
 * @date: 2019
 */
@RestController
@RequestMapping("/api/upload")
public class UploadController {

    /**
     * @auther: Zy
     * @method getQiNiuToken
     * 功能描述: 查询七牛上传token
     * @params: []
     * @return: * @return : java.lang.String
     * @date: 2019-01-09 16:02:23
     */
    @RequestMapping("getQiNiuToken")
    public Result getQiNiuToken() {
        Props props = new Props("workConfig.properties", "utf-8");
        String acceseKey = props.getStr("acceseKey");
        String sercretKey = props.getStr("sercretKey");
        String bucket = props.getStr("bucket");//空间名
        Auth auth = Auth.create(acceseKey, sercretKey);
        String upToken = auth.uploadToken(bucket);
        System.out.println(upToken);
        return ResultUtil.success(upToken);
    }

    /**
     * @auther: Zy
     * @method imageUploadQiNiu
     * 功能描述: 上传单张图片到七牛
     * @params: [file]
     * @return: * @return : java.util.Map
     */
    @RequestMapping(value = "uploadOneImg", method = RequestMethod.POST)
    public Map imageUploadQiNiu(@RequestParam("file") MultipartFile file) throws IOException {
        Props props = new Props("workConfig.properties", "utf-8");
        String acceseKey = props.getStr("acceseKey");
        String sercretKey = props.getStr("sercretKey");
        String bucket = props.getStr("bucket");//空间名
        String doMain = props.getStr("domain");//域名
        Map map = new HashMap();
        if (!file.isEmpty()) {
            String name = file.getOriginalFilename();
            name = name.substring(0, name.lastIndexOf(".")) + new Date().getTime() + name.substring(name.lastIndexOf("."));
            // 构造一个带指定Zone对象的配置类
            Configuration cfg = new Configuration(Zone.zone0());
            // ...其他参数参考类注释
            UploadManager uploadManager = new UploadManager(cfg);
            Auth auth = Auth.create(acceseKey, sercretKey);
            String upToken = auth.uploadToken(bucket);
            uploadManager.put(file.getInputStream(), name, upToken, null, null);
            Map pic = new HashMap();
            pic.put("src", doMain + "/" + name);
            pic.put("title", "pic");
            map.put("data", pic);
        }
        map.put("code", 0);
        return map;
    }

    /**
     * @auther: Zy
     * @method imageUploadQiNiu
     * 功能描述: 上传多张图片到七牛
     * @params: [files]
     * @return: * @return : java.util.Map
     */
    @RequestMapping(value = "uploadManyImg", method = RequestMethod.POST)
    public Map imageUploadQiNiu(@RequestParam("file") MultipartFile[] files) throws IOException {
        Props props = new Props("workConfig.properties", "utf-8");
        String acceseKey = props.getStr("acceseKey");
        String sercretKey = props.getStr("sercretKey");
        String bucket = props.getStr("bucket");
        String doMain = props.getStr("domain");
        List<String> listImagePath = new ArrayList<String>();
        Map map = new HashMap();
        for (MultipartFile mf : files) {
            if (!mf.isEmpty()) {
                String name = mf.getOriginalFilename() + new Date().getTime();
                name = name.substring(0, name.lastIndexOf(".")) + new Date().getTime() + name.substring(name.lastIndexOf("."));
                // 构造一个带指定Zone对象的配置类
                Configuration cfg = new Configuration(Zone.zone0());
                // ...其他参数参考类注释
                UploadManager uploadManager = new UploadManager(cfg);
                Auth auth = Auth.create(acceseKey, sercretKey);
                String upToken = auth.uploadToken(bucket);
                uploadManager.put(mf.getInputStream(), name, upToken, null, null);
                listImagePath.add(doMain + "/" + name);
            }
        }
        map.put("data", listImagePath);
        map.put("errno", 0);
        return map;
    }

    /**
     * @auther: Zy
     * @method uploadFile
     * 功能描述: 文件上传
     * @params: [file]
     * @return: * @return : java.util.Map
     */
    @RequestMapping(value = "uploadFile", method = RequestMethod.POST)
    public Map uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        Props props = new Props("workConfig.properties", "utf-8");
        String acceseKey = props.getStr("acceseKey");
        String sercretKey = props.getStr("sercretKey");
        String bucket = props.getStr("bucket");
        String doMain = props.getStr("domain");
        Map map = new HashMap();
        if (!file.isEmpty()) {
            String name = file.getOriginalFilename();
            name = name.substring(0, name.lastIndexOf(".")) + name.substring(name.lastIndexOf("."));
            // 构造一个带指定Zone对象的配置类
            Configuration cfg = new Configuration(Zone.zone0());
            // ...其他参数参考类注释
            UploadManager uploadManager = new UploadManager(cfg);
            Auth auth = Auth.create(acceseKey, sercretKey);
            String upToken = auth.uploadToken(bucket);
            uploadManager.put(file.getInputStream(), name, upToken, null, null);
            Map pic = new HashMap();
            pic.put("src", doMain + name);
            pic.put("title", "pic");
            map.put("data", pic);
        }
        map.put("code", 0);
        return map;
    }

//******************************************************上传到本地*********************************************************

    /**
     * @auther: Zy
     * @method uploadImgLocal
     * 功能描述: 上传文件到本地
     * @params: [files, request]
     * @return: * @return : com.alibaba.fastjson.JSONObject
     */
    @RequestMapping(value = "uploadImgLocal", method = RequestMethod.POST)
    public Object uploadImgLocal(@RequestParam("file") MultipartFile[] files, HttpServletRequest request) throws IOException {
        List<Map> listImagePath = new ArrayList<>();
        for (MultipartFile file : files) {
            String path = "";
            // 先判断文件是否为空
            if (!file.isEmpty()) {
                // 获得原始文件名
                String fileName = file.getOriginalFilename();
                // 重命名文件
                String newfileName = (int) (Math.random() * 1000000) + fileName;
                //request.getSession().getServletContext().getRealPath("/")表示当前项目的根路径，如
                //D:\Workspaces\eclipse_luna\.metadata\.plugins\org.eclipse.wst.server.core\tmp3\wtpwebapps\sky\
                //获得物理路径webapp所在路径
                String pathRoot = request.getSession().getServletContext().getRealPath("/WEB-INF/");
                System.out.println(pathRoot);
                // 项目下相对路径
                path = "/files/" + newfileName;

                // 创建文件实例
                File tempFile = new File(pathRoot + path);
                // 判断父级目录是否存在，不存在则创建
                if (!tempFile.getParentFile().exists()) {
                    tempFile.getParentFile().mkdir();
                }
                // 判断文件是否存在，否则创建文件（夹）
                if (!tempFile.exists()) {
                    tempFile.mkdir();
                }
                try {
                    // 将接收的文件保存到指定文件中
                    file.transferTo(tempFile);
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // 方法一：model属性也行
                /*model.addAttribute("fileUrl", path); //保存路径，用于jsp页面回显*/
                // 方法二：Request域属性也行，两个二选一即可。
                // request.setAttribute("fileUrl", path);
                String path1 = request.getContextPath();
                String basePath = request.getScheme() + "://"
                        + request.getServerName() + ":" + request.getServerPort()
                        + path1 + "/";
                // getWiewPath方法里就处理了一些路径，相当于转发forward，返回 return "cms/notices/upload";
                //basePath + path/*getViewPath("upload")*/; // 转发到upload.jsp页面
                LinkedHashMap<String, String> hashMap = new LinkedHashMap<>();
                hashMap.put("fileName", newfileName);
                hashMap.put("filePath", basePath + path);//绝对路径
                hashMap.put("path", path);//相对经
                listImagePath.add(hashMap);
            }
        }
        return listImagePath;
    }

    /**
     * @auther: Zy
     * @method fileUploadLocal
     * 功能描述: 上传文件到本地
     * @params: [files, request]
     * @return: * @return : com.alibaba.fastjson.JSONObject
     * @date: 2019-01-09
     */
    @RequestMapping(value = "fileUploadLocal", method = RequestMethod.POST)
    public JSONObject fileUploadLocal(@RequestParam("file") MultipartFile[] files, HttpServletRequest request) throws IOException {
        List<Map> listImagePath = new ArrayList<>();
        String imgSrc = "";
        String imgTitle = "";
        String xdPath = "";
        for (MultipartFile file : files) {
            String path = "";
            // 先判断文件是否为空
            if (!file.isEmpty()) {
                // 获得原始文件名
                String fileName = file.getOriginalFilename();
                // 重命名文件
                String newfileName = (int) (Math.random() * 1000000) + fileName;
                //获得物理路径webapp所在路径
                String pathRoot = request.getSession().getServletContext().getRealPath("/WEB-INF/");
                System.out.println(pathRoot);
                // 项目下相对路径
                path = "files/" + newfileName;

                // 创建文件实例
                File tempFile = new File(pathRoot + path);
                // 判断父级目录是否存在，不存在则创建
                if (!tempFile.getParentFile().exists()) {
                    tempFile.getParentFile().mkdir();
                }
                // 判断文件是否存在，否则创建文件（夹）
                if (!tempFile.exists()) {
                    tempFile.mkdir();
                }

                try {
                    // 将接收的文件保存到指定文件中
                    file.transferTo(tempFile);
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                // 方法一：model属性也行
                /*model.addAttribute("fileUrl", path); //保存路径，用于jsp页面回显*/
                // 方法二：Request域属性也行，两个二选一即可。
                // request.setAttribute("fileUrl", path);
                String path1 = request.getContextPath();
                String basePath = request.getScheme() + "://"
                        + request.getServerName() + ":" + request.getServerPort()
                        + path1 + "/";
                // getWiewPath方法里就处理了一些路径，相当于转发forward，返回 return "cms/notices/upload";

                //basePath + path/*getViewPath("upload")*/; // 转发到upload.jsp页面
                LinkedHashMap<String, String> hashMap = new LinkedHashMap<>();
                imgTitle = newfileName;
                imgSrc = basePath + path;
                xdPath = path;
                hashMap.put("fileName", imgTitle);//文件名称
                hashMap.put("filePath", imgSrc);//绝对路径
                hashMap.put("path", path);//相对经
                listImagePath.add(hashMap);

            }
        }
        JSONObject obj = new JSONObject();
        JSONObject object = new JSONObject();
//        object.put("src", imgSrc);//绝对路径
        object.put("src", xdPath);//相对经
        object.put("title", imgTitle);
        obj.put("data", object);
        obj.put("code", 200);
        return obj;
    }
}
